package com.mindao.app.ued.service;

import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.mindao.app.ued.utils.ZooKeeperKeyConstants;
import com.mindao.utils.config.EaCommonUtils;

/**
/* 版权所有： 广州敏道科技有限公司
/*
/* 功能描述：
/*
/* 创 建 人：李国才
/* 创建时间：2016年8月9日 下午1:08:04 	
 **/
@Component ("zooKeeperService")
@Scope("singleton")
public class ZooKeeperServiceImpl implements ZooKeeperService{
	private final Logger log = LoggerFactory.getLogger(ZooKeeperServiceImpl.class);
	
	private ZooKeeper zk =null;
	@Override
	public String getParaFromZookeeper(String keyName) {
		if (zk!=null){
			try{
				String path="/"+keyName;
				Stat  stat =zk.exists(path, true);
				if (stat!=null)	{	
					String v=new String(zk.getData(path,true,null));
					log.info("从Zookeeper读取参数keyName："+v);
					return v;
				}
			} catch (KeeperException e) {
				log.error(e.getMessage());
			} catch (InterruptedException e) {
				log.error(e.getMessage());
			} 		
	    }
		return null;
	}
	
	@PostConstruct
	public void init(){
		if (zk==null){
			System.out.println("===================初始化============================");
			try {
				zk = new ZooKeeper("120.76.44.235:2181", 
				        6000, new Watcher() { 
				            // 监控所有被触发的事件
				            public void process(WatchedEvent event) { 
				            	log.info("已经触发了" + event.getType() + "事件！");
				                if (("/"+ZooKeeperKeyConstants.prizeNumber).equals(event.getPath())){
				                	
				                	String tmps= getParaFromZookeeper(ZooKeeperKeyConstants.prizeNumber);
				            		if (tmps!=null){
				            			EventPrizeService eventPrizeService=(EventPrizeService)EaCommonUtils.getBean("eventPrizeService");
				            			Integer prizeNumber=Integer.valueOf(tmps);
				            			eventPrizeService.setPrizeNumber(prizeNumber);
				            		}			                	
				                	
				                }
				            } 
				        });
			} catch (IOException e) {
				log.error(e.getMessage());
			}
		}
	}
	@PreDestroy
	public void preDestory(){
		if (zk!=null){
			try {
				zk.close();
			} catch (InterruptedException e) {
				log.error(e.getMessage());
			} 
		}
	}

	@Override
	public boolean setParaFromZookeeper(String keyName,String val) throws Exception{
		if (zk!=null){
			try {
				Stat  stat =zk.exists("/"+keyName, true);//true表示通知watcher
				if (stat!=null)	{
					zk.setData("/"+keyName, val.getBytes(), -1);
				}else{
					 zk.create("/"+keyName, val.getBytes(), Ids.OPEN_ACL_UNSAFE,
							 CreateMode.PERSISTENT); 
				}
				 return true;
			} catch (KeeperException e) {
				log.error(e.getMessage());
				throw e;
			} catch (InterruptedException e) {
				log.error(e.getMessage());
				throw e;
			} 	
		}else{
			log.error("zk==null");
			throw new Exception("zookeeper初始化时出错，zk=null");
		}
 
	}
	
	public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
		ZooKeeper zk = new ZooKeeper("120.76.44.235:2181", 
		        6000, new Watcher() { 
		            // 子节点监控所有被触发的事件
		            public void process(WatchedEvent event) { 
		                System.out.println("已经触发了" + event.getType() + "事件！");
		                if (("/"+ZooKeeperKeyConstants.prizeNumber).equals(event.getPath())){
		                	
		                }
		            } 
		        });
		Stat  stat =zk.exists("/aaa", true);
		System.out.println(stat);
		if (stat!=null)	{
			
		}
	}

}
